#include "SimpleSC.h"

/*B-----------SimpleServer------------*/
bool SimpleServer::Listen(const char* addr)
{
	if (!InitSockets()) return 1;
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == SOCKET_ERROR) return 1;

	sockaddr_in sockAddr = socketAddr(addr);
	if (bind(sock, (struct sockaddr*) &sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)
		return false;
	if (listen(sock, SOMAXCONN) == SOCKET_ERROR)
		return false;

	state = STATE_LISTEN;
	return true;
}

bool SimpleServer::Accept(CSocket &cSock)
{
	int size;
	if (!InitSockets()) return false;
	size = sizeof(cSock.sockAddr);
	if ((cSock.sock = accept(sock, (struct sockaddr*) &cSock.sockAddr, &size))== SOCKET_ERROR)
		return false;

	state = STATE_ACCEPT;
	return true;
}

bool SimpleServer::Send(CSocket cSock, const char* buf, int len)
{
	if ((send(cSock.sock, buf, len, 0))== SOCKET_ERROR)
		return false;
	return true;
}

bool SimpleServer::isRead()
{
	timeval tv = {0, 50};
	fd_set rfd;
	FD_ZERO(&rfd);
	FD_SET(sock, &rfd);
	if (select(0, &rfd, 0, 0, &tv)) return true;
	return false;
}

char* SimpleServer::Recv(CSocket cSock, int &len, int maxlen)
{
	char* buf = new char[maxlen];
	int ret = recv(cSock.sock, buf, maxlen, 0);
	if (ret == SOCKET_ERROR) return NULL;
	if (ret == 0) return NULL;
	len = ret;
	return buf;
}
/*E-----------SimpleServer------------*/

/*B-----------SimpleClient------------*/
bool SimpleClient::Connect(const char* addr)
{
	if (!InitSockets()) return false;
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == SOCKET_ERROR) return false;

	cSock.sock = sock;
	sockaddr_in sockAddr = socketAddr(addr);
	if (connect(sock, (struct sockaddr*) &sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)
		return false;
	cSock.sockAddr = sockAddr;
	state = STATE_CONNECT;
	return 0;
}

bool SimpleClient::Send(const char* buf, int len)
{
	if ((send(cSock.sock, buf, len, 0))== SOCKET_ERROR)
	{
		state = STATE_NONE;
		return false;
	}
	return true;
}

char* SimpleClient::Recv(int &len, int maxlen)
{
	char* buf = new char[maxlen];
	int ret = recv(sock, buf, maxlen, 0);
	if (ret==0) return NULL;
	if (ret==SOCKET_ERROR)
	{
		state = STATE_NONE;
		return NULL;
	}
	len = ret;
	return buf;
}

bool SimpleClient::isRead()
{
	timeval tv = {0, 50};
	fd_set rfd;
	FD_ZERO(&rfd);
	FD_SET(cSock.sock, &rfd);
	if (select(0, &rfd, 0, 0, &tv)) return true;
	return false;
}

/*E-----------SimpleClient------------*/